package com.sxf.core.validator;

import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.text.SimpleDateFormat;

/**
 * @author zhangfangrui
 * @title: DatePatternValid
 * @description: 日期格式校验
 * @date 2020/8/2515:54
 */
public class DateValid implements ConstraintValidator<DateMatcher,String> {
    private DateMatcher dateMatcher = null;

    @Override
    public void initialize(DateMatcher dateMatcher) {
        this.dateMatcher = dateMatcher;
    }

    @Override
    public boolean isValid(String dateStr, ConstraintValidatorContext constraintValidatorContext) {
        if(!this.dateMatcher.required() && StringUtils.isEmpty(dateStr)){
            return true;
        }
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(this.dateMatcher.format());
            sdf.parse(dateStr);
        } catch (Exception e) {
            return false;
        }
        return true;
    }
}
